package com.leyou.service;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.item.client.ItemClient;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpuDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.SpringTemplateEngine;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Eric
 * @version v1.0
 * @package com.leyou.controller
 * @date 2019/7/3 16:51
 * @description:
 **/
@Service
@Slf4j
public class PageService {


    @Autowired
    private ItemClient itemClient;

    @Autowired
    private SpringTemplateEngine templateEngine;

    @Value("${ly.static.itemDir}")
    private String itemDir;
    @Value("${ly.static.itemTemplate}")
    private String itemTemplate;


    /**
     * 商品详情展示的查询
     * @param spuId
     * @return
     */
    public Map<String, Object> loadDate(Long spuId) {

        //创建一个Map集合封装数据
        Map<String, Object> map =new HashMap<>();
        //查询spu
        SpuDTO spuDTO = itemClient.querySpuBySpuId(spuId);
        //查询分类集合
        List<CategoryDTO> categories = itemClient.queryCategoryByIds(spuDTO.getCategoryIds());
        //查询品牌
        BrandDTO brand = itemClient.queryBrandById(spuDTO.getBrandId());
        //查询规格组及规格参数
        List<SpecGroupDTO> specs = itemClient.querySpecs(spuDTO.getCid3());

        //封装数据
        map.put("categories",categories);
        map.put("brand",brand);
        map.put("spuName",spuDTO.getName());
        map.put("subTitle",spuDTO.getSubTitle());
        map.put("detail",spuDTO.getSpuDetail());
        map.put("skus",spuDTO.getSkus());
        map.put("specs",specs);
        return map;
    }

    public void createItemHtml(Long id) {
        // 上下文，准备模型数据
        Context context = new Context();
        // 调用之前写好的加载数据方法
        context.setVariables(loadDate(id));
        // 准备文件路径
        File dir = new File(itemDir);
        if (!dir.exists()) {
            if (!dir.mkdirs()) {
                // 创建失败，抛出异常
                log.error("【静态页服务】创建静态页目录失败，目录地址：{}", dir.getAbsolutePath());
                throw new LyException(ExceptionEnum.DIRECTORY_WRITER_ERROR);
            }
        }
        File filePath = new File(dir, id + ".html");
        // 准备输出流
        try (PrintWriter writer = new PrintWriter(filePath, "UTF-8")) {
            templateEngine.process(itemTemplate, context, writer);
        } catch (IOException e) {
            log.error("【静态页服务】静态页生成失败，商品id：{}", id, e);
            throw new LyException(ExceptionEnum.FILE_WRITER_ERROR);
        }
    }


    public void deleteItemHtml(Long id) {
        File dir = new File(itemDir,id+".html");
        if (dir.exists()){
            if (!dir.delete()){
                log.error("【静态页服务】静态页删除失败，商品id：{}", id);
                throw new LyException(ExceptionEnum.FILE_WRITER_ERROR);
            }
        }
    }
}
